package com.fenshi.interactor.imp;

import android.content.Context;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.android.volley.Request;
import com.android.volley.VolleyError;
import com.fenshi.bean.RequestBean;
import com.fenshi.bean.UserBean;
import com.fenshi.interactor.LoginInteractor;
import com.fenshi.presenter.listener.RequestListener;
import com.fenshi.until.MethodCode;
import com.fenshi.until.MethodType;
import com.quickdv.helper.NetWorkImp;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by Administrator on 2015/9/14.
 */
public class LoginInteracorImp extends NetWorkImp implements LoginInteractor {


    protected RequestListener listener;

    public LoginInteracorImp(Context c) {
        super(c);
    }

    public LoginInteracorImp(Context c, RequestListener<UserBean> listener){
        this(c);
        this.listener = listener;
    }

    @Override
    protected void onRequestSuccess(Object tag, JSONObject result) {
        JSONObject response = result.getJSONObject(MethodCode.responseContent_key);
        int statue = response.getInteger(MethodCode.responseStatue);

        if (statue == (MethodCode.NetState.SUCCESS.getValue())) {

            if (tag.toString().equals(MethodType.LOGIN)) {
                JSONObject obj = response.getJSONObject(MethodCode.OBJECT);
                UserBean bean = JSON.toJavaObject(obj.getJSONObject("userBean"), UserBean.class);
                if (bean.isRole()) listener.Success(tag + "", bean);
                else listener.Error(tag+"","该用户不是管理员");
            }
        }else
            listener.Error(tag + "", "用户名密码错误");
    }

    @Override
     protected void onRequestExcption(VolleyError error) {
        listener.Exception(null,error);
    }

    @Override
    public void login(String userName, String pwd, String token) {
        RequestBean bean = new RequestBean();
        Map<String, Object> params = new HashMap<>();
        params.put("userName", userName);
        params.put("passWord", pwd);
//        params.put("token",token);
//        params.put("sceritKey","");
//        params.put("accessKey","");
        bean.setRequestParams(params);
        bean.setRequestCode(MethodType.LOGIN);
        addFastJsonQueue(Request.Method.POST, MethodType.LOGIN, (JSONObject) JSON.toJSON(bean));
        startRequest();
    }
}
